<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <!-- 引入 Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>

<body>
<div class="container mt-5">

    <!-- 添加用户按钮，触发模态框 -->
    <button type="button" class="btn btn-primary mb-3" data-bs-toggle="modal" data-bs-target="#addUserModal">
        添加用户
    </button>

    <!-- 刷新按钮 -->
    <button type="button" class="btn btn-warning mb-3" onclick="loadUserList()">
        <i class="fa-solid fa-rotate"></i> 刷新
    </button>

    <!-- 搜索用户表单 -->
    <form method="post" class="mb-5" onsubmit="return searchUser(event)">
        <div class="input-group">
            <label for="searchName" class="input-group-text">姓名:</label>
            <input type="text" id="searchName" name="name" class="form-control" placeholder="输入用户名模糊查询">
            <button type="submit" class="btn btn-secondary">搜索</button>
        </div>
    </form>

    <div id="userList">
        <!-- 用户列表将通过 AJAX 动态加载 -->
    </div>
</div>

<!-- 添加用户模态框 -->
<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addUserModalLabel">添加用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addUserForm">
                    <div class="mb-3">
                        <label for="name" class="form-label">姓名:</label>
                        <input type="text" id="name" name="name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label for="age" class="form-label">年龄:</label>
                        <input type="number" id="age" name="age" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label for="statue" class="form-label">状态:</label>
                        <input type="text" id="statue" name="statue" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label for="gender" class="form-label">性别:</label>
                        <input type="text" id="gender" name="gender" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label for="phone" class="form-label">电话:</label>
                        <input type="text" id="phone" name="phone" class="form-control" required>
                    </div>
                    <button type="button" class="btn btn-primary" onclick="addUser()">添加</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 修改用户模态框 -->
<div class="modal fade" id="updateUserModal" tabindex="-1" aria-labelledby="updateUserModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="updateUserModalLabel">修改用户信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="updateUserForm">
                    <input type="hidden" id="updateId" name="id">
                    <div class="mb-3">
                        <label for="updateName" class="form-label">姓名:</label>
                        <input type="text" id="updateName" name="name" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label for="updateAge" class="form-label">年龄:</label>
                        <input type="number" id="updateAge" name="age" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label for="updateStatue" class="form-label">状态:</label>
                        <input type="text" id="updateStatue" name="statue" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label for="updateGender" class="form-label">性别:</label>
                        <input type="text" id="updateGender" name="gender" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label for="updatePhone" class="form-label">电话:</label>
                        <input type="text" id="updatePhone" name="phone" class="form-control">
                    </div>
                    <button type="button" class="btn btn-success" onclick="updateUser()">修改</button>
                    <button type="button" class="btn btn-danger" data-bs-dismiss="modal">取消</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 引入 Font Awesome -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
<!-- 引入 Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function showUpdateForm(id, name, age, statue, gender, phone) {
        document.getElementById('updateId').value = id;
        document.getElementById('updateName').value = name;
        document.getElementById('updateAge').value = age;
        document.getElementById('updateStatue').value = statue;
        document.getElementById('updateGender').value = gender;
        document.getElementById('updatePhone').value = phone;
        // 显示修改用户模态框
        var modal = new bootstrap.Modal(document.getElementById('updateUserModal'));
        modal.show();
    }

    function deleteUser(id) {
        if (confirm('确定要删除该用户吗？')) {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/deleteUser', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    if (xhr.responseText === 'true') {
                        showSuccess('操作成功！', '用户已经删除');
                        loadUserList();
                    } else {
                        showError('操作失败！', '用户删除失败');
                    }
                }
            };
            xhr.send('id=' + id);
        }
    }

    function searchUser(event) {
        // 阻止表单的默认提交行为（页面刷新）
        if (event) {
            event.preventDefault();
        }
        var name = document.getElementById('searchName').value;
        document.getElementById('searchName').value = "";
        var xhr = new XMLHttpRequest();
        if (name === null || name.trim() === "") {
            loadUserList();
        } else {
            xhr.open('POST', '/searchUser', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    // 解析JSON数据
                    console.log(xhr.responseText)
                    var data = JSON.parse(xhr.responseText);
                    var table = '<table class="table table-striped table-bordered">\n';
                    table += '<thead>\n';
                    table += '<tr>\n';
                    table += '<th>ID</th>\n';
                    table += '<th>姓名</th>\n';
                    table += '<th>年龄</th>\n';
                    table += '<th>状态</th>\n';
                    table += '<th>性别</th>\n';
                    table += '<th>电话</th>\n';
                    table += '<th>操作</th>\n';
                    table += '</tr>\n';
                    table += '</thead>\n';
                    table += '<tbody>\n';
                    if (data.rows && data.rows.length > 0) {
                        data.rows.forEach(function (row) {
                            table += '<tr>\n';
                            table += '<td>' + row.id + '</td>\n';
                            table += '<td>' + row.name + '</td>\n';
                            table += '<td>' + row.age + '</td>\n';
                            table += '<td>' + row.statue + '</td>\n';
                            table += '<td>' + row.gender + '</td>\n';
                            table += '<td style="width: 220px">' + row.phone + '</td>\n';
                            // 这里可以添加操作按钮，比如修改、删除按钮
                            table += '<td style="width: 140px"><button type="button" class="btn btn-info" onclick="showUpdateForm(' + row.id + ',\'' + row.name + '\',' + row.age + ',\'' + row.statue + '\',\'' + row.gender + '\',\'' + row.phone + '\')">修改</button> <button type="button" class="btn btn-primary" onclick="deleteUser(' + row.id + ')">删除</button></td>\n';
                            table += '</tr>\n';
                        });
                    }
                    table += '</tbody>\n';
                    table += '</table>\n';
                    document.getElementById('userList').innerHTML = table;
                }
            };
            xhr.send('name=' + encodeURIComponent(name));
        }
    }

    function loadUserList() {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/selectAllUser', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                // 解析JSON数据
                var data = JSON.parse(xhr.responseText);
                var table = '<table class="table table-striped table-bordered">\n';
                table += '<thead>\n';
                table += '<tr>\n';
                table += '<th>ID</th>\n';
                table += '<th>姓名</th>\n';
                table += '<th>年龄</th>\n';
                table += '<th>状态</th>\n';
                table += '<th>性别</th>\n';
                table += '<th>电话</th>\n';
                table += '<th>操作</th>\n';
                table += '</tr>\n';
                table += '</thead>\n';
                table += '<tbody>\n';
                if (data.rows && data.rows.length > 0) {
                    data.rows.forEach(function (row) {
                        table += '<tr>\n';
                        table += '<td>' + row.id + '</td>\n';
                        table += '<td>' + row.name + '</td>\n';
                        table += '<td>' + row.age + '</td>\n';
                        table += '<td>' + row.statue + '</td>\n';
                        table += '<td>' + row.gender + '</td>\n';
                        table += '<td style="width: 220px">' + row.phone + '</td>\n';
                        // 这里可以添加操作按钮，比如修改、删除按钮
                        table += '<td style="width: 140px"><button type="button" class="btn btn-info" onclick="showUpdateForm(' + row.id + ',\'' + row.name + '\',' + row.age + ',\'' + row.statue + '\',\'' + row.gender + '\',\'' + row.phone + '\')">修改</button> <button type="button" class="btn btn-primary" onclick="deleteUser(' + row.id + ')">删除</button></td>\n';
                        table += '</tr>\n';
                    });
                }
                table += '</tbody>\n';
                table += '</table>\n';
                document.getElementById('userList').innerHTML = table;
            }
        };
        xhr.send();
    }

    function updateUser() {
        var id = document.getElementById('updateId').value;
        var name = document.getElementById('updateName').value;
        var age = document.getElementById('updateAge').value;
        var statue = document.getElementById('updateStatue').value;
        var gender = document.getElementById('updateGender').value;
        var phone = document.getElementById('updatePhone').value;

        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/updateUser', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                if (xhr.responseText === 'true') {
                    showSuccess('操作成功！', '修改用户信息成功！');
                    // 重新加载用户列表
                    loadUserList();
                    // 关闭模态框
                    var modal = bootstrap.Modal.getInstance(document.getElementById('updateUserModal'));
                    modal.hide();
                } else {
                    showError('操作失败！', '修改用户信息失败！');
                }
            }
        };
        var data = 'id=' + id + '&name=' + encodeURIComponent(name) + '&age=' + age + '&statue=' + encodeURIComponent(statue) + '&gender=' + encodeURIComponent(gender) + '&phone=' + encodeURIComponent(phone);
        xhr.send(data);
    }

    function addUser() {
        var name = document.getElementById('name').value;
        var age = document.getElementById('age').value;
        var statue = document.getElementById('statue').value;
        var gender = document.getElementById('gender').value;
        var phone = document.getElementById('phone').value;

        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/addUser', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                if (xhr.responseText === 'true') {
                    var modal = bootstrap.Modal.getInstance(document.getElementById('addUserModal'));
                    modal.hide();
                    showSuccess('操作成功！', '添加用户成功！');
                    // 重新加载用户列表
                    window.location.reload();
                } else {
                    showError('操作失败！', '添加用户失败！');
                }
            }
        };
        var data = 'name=' + encodeURIComponent(name) + '&age=' + age + '&statue=' + encodeURIComponent(statue) + '&gender=' + encodeURIComponent(gender) + '&phone=' + encodeURIComponent(phone);
        xhr.send(data);
    }

    function showSuccess(title, text = '', timer = 3000) {
        Swal.fire({
            icon:'success',
            title: title,
            text: text,
            timer: timer,
            showConfirmButton: false,
            toast: true, // 可选：设置为 Toast 模式（更轻量）
            position: 'top-end', // 可选：位置（右上角）
        });
    }

    function showError(title, text = '', timer = 2000) {
        Swal.fire({
            icon: 'error',
            title: title,
            text: text,
            timer: timer || undefined, // 0 时不设置 timer
            showConfirmButton:!!timer, // 如果 timer=0，显示确认按钮
        });
    }

    // 页面加载时自动加载用户列表
    window.onload = loadUserList;
</script>
</body>

</html>